package com.jwdf.uda.app;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.multidex.MultiDex;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.RemoteViews;

import com.jwdf.uda.BuildConfig;
import com.jwdf.uda.R;
import com.jwdf.uda.event.LongTaskEvent;
import com.jwdf.uda.push.PushIntentService;
import com.jwdf.uda.ui.fragment.progress.FloatView;
import com.jwdf.uda.ui.fragment.progress.FloatViews;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.LogUtils;
import com.jwdf.uda.utils.StatisticalUtil;
import com.jwdf.uda.view.imagegetter.Constants;
import com.jwdf.uda.view.recyclerView.PullLoadMoreRecyclerView;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;

/**
 * Created by RD-001 on 2016/4/27.
 */
public class AppContext extends Application {
    protected static final String PREFS_FILE = "gank_device_id.xml";
    protected static final String PREFS_DEVICE_ID = "gank_device_id";
    private static final int MAX_MEMORY_CACHE = 8 * 1024 * 1024;
    protected static String uuid;
    private static AppContext instance;
    public UnlimitedDiskCache discCache;
    private WindowManager.LayoutParams windowParams ;
    private FloatView floatView = null;
    private FloatViews floatViews = null;
    private boolean isDisplay = false;
    private boolean isDisplays = false;
    //应用初始化
    private Runnable initRunnable = new Runnable() {
        @Override
        public void run() {
            //put your logic here!
            StatisticalUtil.init();
            initImageLoader(instance);
            dealUpushMessage();
        }
    };
    private View.OnClickListener floatViewClick = new View.OnClickListener() {

        public void onClick(View v) {
            EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_CLICK));
        }
    };
    public static AppContext getInstance() {
        return instance;
    }
    /**
     * get app version code
     *
     * @param context
     * @return
     */
    public static String getAppVersionName(Context context) {
        if (context != null) {
            PackageManager pm = context.getPackageManager();
            if (pm != null) {
                PackageInfo pi;
                try {
                    pi = pm.getPackageInfo(context.getPackageName(), 0);
                    if (pi != null) {
                        return pi.versionName;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * 获取包名
     *
     * @param context
     * @return
     */
    public static String getAppPackageName(Context context) {
        if (context != null) {
            PackageManager pm = context.getPackageManager();
            if (pm != null) {
                PackageInfo pi;
                try {
                    pi = pm.getPackageInfo(context.getPackageName(), 0);
                    if (pi != null) {
                        return pi.packageName;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * get app version code
     *
     * @param context
     * @return
     */
    public static int getAppVersionCode(Context context) {
        if (context != null) {
            PackageManager pm = context.getPackageManager();
            if (pm != null) {
                PackageInfo pi;
                try {
                    pi = pm.getPackageInfo(context.getPackageName(), 0);
                    if (pi != null) {
                        return pi.versionCode;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return -1;
    }
    /**
     * 获取渠道名称
     *
     * @param context
     * @return
     */
    public static String getChannel(Context context) {
        return getAppMetaData(context, "UMENG_CHANNEL");
    }
    /**
     * 获取application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值，或者异常)，则返回值为空
     */
    public static String getAppMetaData(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return null;
        }
        String resultData = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        resultData = applicationInfo.metaData.getString(key);
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return resultData;
    }
    public static String getUDID(Context context) {
        if (uuid == null) {
            synchronized (PREFS_FILE) {
                if (uuid == null) {
                    final SharedPreferences prefs = context.getSharedPreferences(PREFS_FILE, 0);
                    final String id = prefs.getString(PREFS_DEVICE_ID, null);

                    if (id != null) {
                        // Use the ids previously computed and stored in the prefs file
                        uuid = id;
                    } else {

                        final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

                        // Use the Android ID unless it's broken, in which case fallback on deviceId,
                        // unless it's not available, then fallback on a random number which we store
                        // to a prefs file
                        try {
                            if (!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
                            } else {
                                final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
                                uuid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")).toString() : UUID.randomUUID().toString();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }

                        // Write the value out to the prefs file
                        prefs.edit().putString(PREFS_DEVICE_ID, uuid).commit();
                    }
                }
            }
        }
        return uuid;
    }
    /**
     * install package normal by system intent
     *
     * @param context
     * @param filePath file path of package
     * @return whether apk exist
     */
    public static boolean installNormal(Context context, String filePath) {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File file = new File(filePath);
        if (file == null || !file.exists() || !file.isFile() || file.length() <= 0) {
            return false;
        }

        i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
        return true;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initRunnable.run();
        LogUtils.syncAppDebugMode(getApplicationContext());
        BGASwipeBackHelper.init(this, null);
        if(Constants.Config.DEVELOPER_MODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDialog().build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyDeath().build());
        }

        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        this.discCache = new UnlimitedDiskCache(cacheDir);
        initImageLoader(getApplicationContext(), this.discCache);
    }
    @Override
    public void onTerminate() {
        ConfigUtils.setHandledInvalid(getApplicationContext(),false);
        super.onTerminate();
    }
    @Override
    public void onLowMemory() {
        ConfigUtils.setHandledInvalid(getApplicationContext(),false);
        super.onLowMemory();
    }
    @Override
    public void onTrimMemory(int level) {
        ConfigUtils.setHandledInvalid(getApplicationContext(),false);
        super.onTrimMemory(level);
    }
    public static void initImageLoader(Context context,UnlimitedDiskCache discCache) {

        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .cacheInMemory(true)
                .showImageForEmptyUri(R.drawable.default_bg)
                .showImageOnFail(R.drawable.default_bg).showImageOnLoading(R.drawable.default_bg)
                .cacheOnDisk(true).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
//                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .diskCache(discCache) // default
//                .diskCacheSize(50 * 1024 * 1024) // 50 Mb
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .defaultDisplayImageOptions(displayImageOptions) // default
                .writeDebugLogs() // Remove for release app
                .build();

//        config = ImageLoaderConfiguration.createDefault(context);
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }
    private synchronized void initImageLoader(Context context) {
        DisplayImageOptions options = new DisplayImageOptions.Builder().imageScaleType(ImageScaleType.EXACTLY).bitmapConfig(Bitmap.Config.RGB_565).cacheInMemory(true).showImageForEmptyUri(R.drawable.default_bg).showImageOnFail(R.drawable.default_bg)
                                              .showImageOnLoading(R.drawable.default_bg).cacheOnDisk(true).considerExifParams(true).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).diskCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.FIFO).memoryCache(new LRULimitedMemoryCache(MAX_MEMORY_CACHE))
                                                  .denyCacheImageMultipleSizesInMemory().threadPriority(Thread.NORM_PRIORITY - 2).defaultDisplayImageOptions(options).build();
        ImageLoader.getInstance().init(config);
        ImageLoader.getInstance().handleSlowNetwork(true);
    }
    private void dealUpushMessage() {
        PushAgent pushAgent = PushAgent.getInstance(this);
        pushAgent.setDebugMode(BuildConfig.DEBUG);
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                Log.i("Push", "dealWithCustomMessage--->" + msg.builder_id);
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        //                        // TODO Auto-generated method stub
                        //                        // 对自定义消息的处理方式，点击或者忽略
                        //                        boolean isClickOrDismissed = true;
                        //                        if (isClickOrDismissed) {
                        //                            //自定义消息的点击统计
                        //                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
                        //                        } else {
                        //                            //自定义消息的忽略统计
                        //                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
                        //                        }
                        //                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public Notification getNotification(Context context, UMessage msg) {
                Log.i("Push", "getNotification--->" + msg.builder_id);
                switch(msg.builder_id) {
                    case 1:
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.view_notification);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));
                        builder.setContent(myNotificationView).setSmallIcon(getSmallIconId(context, msg)).setTicker(msg.ticker).setAutoCancel(true);

                        return builder.build();

                    default:
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        return super.getNotification(context, msg);
                }
            }
        };
        pushAgent.setMessageHandler(messageHandler);

        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                Log.i("Push", "dealWithCustomAction--->" + msg.builder_id);
                //                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
            }
        };
        pushAgent.setNotificationClickHandler(notificationClickHandler);

        pushAgent.setPushIntentServiceClass(PushIntentService.class);
    }
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
    public WindowManager.LayoutParams getWindowParams() {
        windowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        windowParams.type=WindowManager.LayoutParams.TYPE_PHONE;
        windowParams.flags=WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        windowParams.format=WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        windowParams.gravity = Gravity.RIGHT | Gravity.TOP;
        windowParams.windowAnimations=android.R.style.Animation_Translucent;
        return windowParams;
    }
    public void removeView() {
        if (!isDisplay)
            return;
        WindowManager windowManager = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
        // 在程序退出(Activity销毁）时销毁悬浮窗口
        windowManager.removeView(floatView);
        isDisplay = false;
    }
    public void createView() {
        if (isDisplay)
            return;
        floatView = new FloatView(this);
        floatView.setOnClickListener(floatViewClick);
        // floatView.setImageResource(R.drawable.ic_launcher);
        // 获取WindowManager
        WindowManager windowManager = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
        // 设置LayoutParams(全局变量）相关参数
        // 显示myFloatView图像
        windowManager.addView(floatView, windowParams);
        isDisplay = true;
    }
    public void removeViews() {
        if (!isDisplays)
            return;
        WindowManager windowManager = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
        // 在程序退出(Activity销毁）时销毁悬浮窗口
        windowManager.removeView(floatViews);
        isDisplays = false;
    }
    public void createViews() {
        if (isDisplays)
            return;
        floatViews = new FloatViews(this);
//        floatViews.setOnClickListener(floatViewClick);
        // floatView.setImageResource(R.drawable.ic_launcher);
        // 获取WindowManager
        WindowManager windowManager = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);
        // 设置LayoutParams(全局变量）相关参数
        // 显示myFloatView图像
        windowManager.addView(floatViews, windowParams);
        isDisplays = true;
    }

}
